import requests
import json
from config import BASE_URL, API_VERSION, TEST_USER, ADMIN_USER, SUCCESS_CODE

class BaseApi:
    def __init__(self):
        self.base_url = f"{BASE_URL}{API_VERSION}"
        self.session = requests.Session()
        self.user_token = None
        self.admin_token = None
        self.use_session_cookie = True  # 默认使用SESSION cookie
        self.session_cookie_value = "YzlkY2ExYzQtNDk5Mi00ZjFjLWI1MDctYjRlNWY0NDMwY2M2"  # 提供的SESSION cookie值
        self.use_basic_auth = True  # 使用Basic认证
        self.basic_auth_value = "Basic cm9vdDo2NjY0NDQ="  # Basic认证值
    
    def login_user(self):
        """用户登录获取token"""
        url = f"{self.base_url}/user/login"
        try:
            response = self.session.post(
                url=url,
                json=TEST_USER
            )
            result = response.json()
            if result.get("code") == SUCCESS_CODE:
                self.user_token = result.get("data", {}).get("token")
                return self.user_token
            return None
        except Exception as e:
            print(f"用户登录失败: {str(e)}")
            return None
    
    def login_admin(self):
        """管理员登录获取token"""
        url = f"{self.base_url}/user/login"
        try:
            response = self.session.post(
                url=url,
                json=ADMIN_USER
            )
            result = response.json()
            if result.get("code") == SUCCESS_CODE:
                self.admin_token = result.get("data", {}).get("token")
                return self.admin_token
            return None
        except Exception as e:
            print(f"管理员登录失败: {str(e)}")
            return None
    
    def get_user_headers(self):
        """获取普通用户请求头"""
        # 创建基础请求头
        headers = {
            "Content-Type": "application/json",
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Host": "121.4.251.221",
            "Origin": "http://121.4.251.221",
            "Referer": "http://121.4.251.221/api/doc.html",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
        }
        
        # 根据配置添加认证信息
        if self.use_basic_auth and self.basic_auth_value:
            headers["Authorization"] = self.basic_auth_value
        else:
            # 如果需要Bearer认证
            if not self.user_token:
                self.login_user()
            if self.user_token:
                headers["Authorization"] = f"Bearer {self.user_token}"
                
        return headers
    
    def get_admin_headers(self):
        """获取管理员请求头"""
        # 创建基础请求头
        headers = {
            "Content-Type": "application/json",
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Host": "121.4.251.221",
            "Origin": "http://121.4.251.221",
            "Referer": "http://121.4.251.221/api/doc.html",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
        }
        
        # 根据配置添加认证信息
        if self.use_basic_auth and self.basic_auth_value:
            headers["Authorization"] = self.basic_auth_value
        else:
            # 如果需要Bearer认证
            if not self.admin_token:
                self.login_admin()
            if self.admin_token:
                headers["Authorization"] = f"Bearer {self.admin_token}"
                
        return headers
    
    def get(self, url, params=None, headers=None, auth_type="user"):
        """发送GET请求"""
        if not headers:
            if auth_type == "admin":
                headers = self.get_admin_headers()
            else:
                headers = self.get_user_headers()
                
        # 如果需要使用SESSION cookie，添加到请求中
        cookies = {}
        if self.use_session_cookie and self.session_cookie_value:
            cookies['SESSION'] = self.session_cookie_value
                
        try:
            response = self.session.get(
                url=url,
                params=params,
                headers=headers,
                cookies=cookies,
                timeout=10
            )
            return response
        except Exception as e:
            print(f"GET请求失败: {str(e)}")
            return None
    
    def post(self, url, data=None, json=None, headers=None, auth_type="user", content_type="json"):
        """发送POST请求"""
        if not headers:
            if auth_type == "admin":
                headers = self.get_admin_headers()
            else:
                headers = self.get_user_headers()
                
        if content_type == "form":
            headers["Content-Type"] = "application/x-www-form-urlencoded"
        
        # 如果需要使用SESSION cookie，添加到请求中
        cookies = {}
        if self.use_session_cookie and self.session_cookie_value:
            cookies['SESSION'] = self.session_cookie_value
        
        try:
            response = self.session.post(
                url=url,
                data=data,
                json=json,
                headers=headers,
                cookies=cookies,
                timeout=10
            )
            return response
        except Exception as e:
            print(f"POST请求失败: {str(e)}")
            return None
    
    def parse_response(self, response):
        """解析响应"""
        if not response:
            return None, "无响应"
            
        try:
            result = response.json()
            return result, None
        except json.JSONDecodeError:
            return None, "响应不是有效的JSON格式"
    
    def format_result(self, result, error=None):
        """格式化结果输出"""
        if error:
            return f"错误: {error}"
        
        if isinstance(result, dict):
            return json.dumps(result, ensure_ascii=False, indent=2)
        return str(result)
    
    def set_session_cookie_status(self, use_cookie):
        """设置是否使用SESSION cookie
        
        Args:
            use_cookie (bool): True表示使用SESSION cookie，False表示不使用
        """
        self.use_session_cookie = use_cookie
    
    def update_session_cookie_value(self, cookie_value):
        """更新SESSION cookie的值
        
        Args:
            cookie_value (str): 新的SESSION cookie值
        """
        self.session_cookie_value = cookie_value
    
    def set_basic_auth_status(self, use_basic_auth):
        """设置是否使用Basic认证
        
        Args:
            use_basic_auth (bool): True表示使用Basic认证，False表示使用Bearer认证
        """
        self.use_basic_auth = use_basic_auth
    
    def update_basic_auth_value(self, auth_value):
        """更新Basic认证的值
        
        Args:
            auth_value (str): 新的Basic认证值
        """
        self.basic_auth_value = auth_value